//
//  STHttpManager.m
//  赛拓
//
//  Created by 王磊 on 8/14/16.
//  Copyright © 2016 立金所. All rights reserved.
//

#import "STHttpManager.h"
#import "AppDelegate.h"
#import "STBasicBean.h"

static STHttpManager *sharedInstance = nil;

@implementation STHttpManager
+ (instancetype)getInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [self new];
    });
    return sharedInstance;
}

- (NSString *)getToken {
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    return delegate.accountBean.token ? delegate.accountBean.token : @"";
}

- (void)requestWithUrlString:(NSString *)urlString andParams:(NSDictionary *)params andStartBlock:(STHttpStartBlock )startBlock andSuccessBlock:(STHttpSuccessBlock )successBlock andFailureBlock:(STHttpFailureBlock )failureBlock {
    
    if (startBlock) {
        
        NSString *token = [self getToken];
        
        NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithDictionary:params];
        
        if (token.length) {
            
            [parameters setObject:token forKey:@"token"];
        }
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        [manager POST:urlString parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            
            if ([NSJSONSerialization isValidJSONObject:responseObject]) {
                
                NSDictionary *json = responseObject;
                
                STBasicBean *basic = [STBasicBean mj_objectWithKeyValues:json];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    successBlock(basic.rescode ,basic.msg,basic.token,basic.sysTime,basic.data,basic.page);
                });
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            
            failureBlock();
            
            [SVProgressHUD showInfoWithStatus:@"网络异常"];
            
        }];
    }
}

@end
